﻿//===============================================================================
// Microsoft patterns & practices Enterprise Library Contribution
// Validation Application Block
//===============================================================================

using System;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection.Emit;

namespace EntLibContrib.Validation.Configuration.Design.UI
{
	/// <summary>
	/// Type Name User Interface
	/// </summary>
	public partial class TypeNameUI : Form
	{
		#region Fields
		private Type t;
		#endregion

		#region Properties
		/// <summary>
		/// Gets the selected type.
		/// </summary>
		/// <value>The selected type.</value>
		public Type SelectedType
		{
			get { return t; }
		}
		#endregion

		#region Construction
		/// <summary>
		/// Initializes a new instance of the <see cref="TypeNameUI"/> class.
		/// </summary>
		public TypeNameUI()
		{
			InitializeComponent();
			txtTypeExists.ForeColor = Color.Black;
		}
		#endregion

		#region Event Handlers
		private void txtTypeName_Leave(object sender, EventArgs e)
		{
		}

		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
		private void btnOk_Click(object sender, EventArgs e)
		{
			try
			{
				t = Type.GetType(txtTypeName.Text, false);
				if (t == null)
				{
					AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(new System.Reflection.AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.ReflectionOnly);
					ModuleBuilder mb = ab.DefineDynamicModule("temp");
					t = mb.DefineType(txtTypeName.Text);
				}
				DialogResult = DialogResult.OK;
				Close();
			}
			catch
			{
				txtTypeExists.ForeColor = Color.Red;
			}
		}

		private void txtTypeName_Enter(object sender, EventArgs e)
		{
			txtTypeExists.ForeColor = Color.Black;
		}

		private void txtTypeName_TextChanged(object sender, EventArgs e)
		{
			txtTypeExists.Visible = (Type.GetType(txtTypeName.Text, false) != null);
		}
		#endregion
	}
}